// echarts 轮播工具
import {EChartsType} from "echarts/types/dist/echarts";
import typeOfUtils from "../type-of-utils";

export interface RotationData {
  setIntervalNum: NodeJS.Timer | null
}

export class RotationUtils {
  public static startSelectAnimate(myChart: EChartsType, seriesIndex: number[], dataLength: number, timeOut: number = 3000): RotationData {
    let count = 0;
    let mouseEnterIs = false
    const oldDispose = myChart.dispose
    const dom = myChart.getDom()
    const runFunc = () => {
      myChart.dispatchAction({
        type: 'downplay',
        seriesIndex: seriesIndex,
      });
      myChart.dispatchAction({
        type: 'highlight',
        seriesIndex: seriesIndex,
        dataIndex: count
      });
      myChart.dispatchAction({
        type: 'showTip',
        seriesIndex: seriesIndex[0],
        dataIndex: count
      });
      count++;
      if (count >= dataLength) {
        count = 0
      }
    }
    runFunc()
    const getTimeNum = () => {
      return setInterval(runFunc, timeOut)
    }
    const result: RotationData = {
      setIntervalNum: getTimeNum()
    }

    function mouseEnter() {
      mouseEnterIs = true
      RotationUtils.clearAnimate(result)
    }

    dom.addEventListener('mouseenter', mouseEnter)
    myChart.dispose = function () {
      dom.removeEventListener('mouseenter', mouseEnter)
      oldDispose.call(this)
    }
    myChart.on('globalout', (e) => {
      mouseEnterIs = false
      result.setIntervalNum = getTimeNum()
      runFunc()
    })
    myChart.on('highlight', (e) => {
      if (mouseEnterIs) {
        // @ts-ignore
        let dataIndex = e.dataIndex
        if (typeOfUtils.isEmpty(dataIndex)) {
          // @ts-ignore
          dataIndex = e.batch?.[0]?.dataIndex || 0
        }
        count = dataIndex
      }
    })
    return result
  }

  public static clearAnimate(data: RotationData) {
    if (data.setIntervalNum) {
      clearInterval(data.setIntervalNum)
      data.setIntervalNum = null
    }
  }
}
